const router = require('express').Router();
const db = require('./../config/dbcofnig')
const upload = require("./../config/uploadconfig")
// 查询医生团队数据
// 团队名称， 负责医生的名称
router.get("/getPageTeam", (req, res) => {
  let { tname, dname } = req.query;


  let sql = "SELECT * FROM `teams` AS t , `teamdoctortable` AS tdt , `doctorstable` AS d  WHERE t.`tid`=tdt.`tid` AND tdt.`did`=d.did";
  let params = [];
  if (!!tname) {
    sql += ` and t.tname = ?`
    params.push(tname)
  }
  if (!!dname) {
    sql += ` and d.dname = ?`
    params.push(dname)
  }

  sql += ";"

  let cb = (err, data) => {
    console.log(sql)
    if (err === null) {
      res.json({ code: 200, msg: '查询成功', data })
    } else {
      res.json({ code: 4001, msg: '查询失败' })
    }
  }

  db.connect(sql, params, cb)
});


// 添加医生团队
router.route("/addDoctorTeam").post(upload.single('tphoto'), async (req, res) => {
  // console.log(req.body);
  let { doctorArr, tname, tdes } = req.body;
  let tphoto = req.file?.filename;
  // async, await写法：
  // let tid = undefined;
  const fn1 = () => {
    return new Promise((resolve, reject) => {
      let sql1 = `insert into teams values(?,?,?,?,?);`
      let params1 = [null, tname, tdes, tphoto, '0']
      let cb = (err, data) => {
        if (err === null) {
          resolve(data.insertId) // tid做为已兑现的结果
        } else {
          reject('插入团队数据时失败')
        }
      }
      db.connect(sql1, params1, cb)
    })
  };

  const fn2 = (tid) => {
    return new Promise((resolve, reject) => {
      let arr = JSON.parse(doctorArr)
      let sql2 = `INSERT INTO teamdoctortable VALUES `
      let params2 = [];
      let sqlStr = [];
      // 循环生成插入的语法和参数；　
      arr.forEach(el => {
        sqlStr.push(`(?,?,?,?)`);
        params2.push(null, tid, el.did, el.manager);//null，必须是小写的
      });
      sql2 += sqlStr.join(",") + ";"
      let cb2 = (err, data) => {
        console.log(err);
        if (err === null) {

          resolve("1");
        } else {
          reject('0');
        }
      }
      db.connect(sql2, params2, cb2)
    })
  };

  // const fn3 = async () => {
  let tid = await fn1();
  let flag = await fn2(tid);
  if (flag === '1') {
    res.json({ code: 200, msg: '添加团队成功' })
  } else {
    res.json({ code: 4001, msg: '添加团队失败' })
  }
  // }
  // fn3();
  //第一个异步：插入团队表的数据
  /*   new Promise((resolve, reject) => {
      let sql1 = `insert into teams values(?,?,?,?,?);`
      let params1 = [null, tname, tdes, tphoto, '0']
      let cb = (err, data) => {
        if (err === null) {
          resolve(data.insertId) // tid做为已兑现的结果
        } else {
          reject('插入团队数据时失败')
        }
      }
      db.connect(sql1, params1, cb)
    })
      // 第2个异步，插入团队医生表的数据
      .then((tid) => {
        console.log('团队的ID', tid);
        return new Promise((resolve, reject) => {
          let arr = JSON.parse(doctorArr)
          let sql2 = `INSERT INTO teamdoctortable VALUES `
          let params2 = [];
          let sqlStr = [];
          // 循环生成插入的语法和参数；　
          arr.forEach(el => {
            sqlStr.push(`(?,?,?,?)`);
            params2.push(null, tid, el.did, el.manager);//null，必须是小写的
          });
          sql2 += sqlStr.join(",") + ";"
          let cb2 = (err, data) => {
            console.log(err);
            if (err === null) {
              // console.log(("11111111111111111"));
              // return Promise. resolve("添加团队成功");
              resolve("添加团队成功");
            } else {
              // console.log(("22222"));
              reject('插入团队医生表失败');
            }
          }
          db.connect(sql2, params2, cb2)
        })
  
      })
      .then(a => {
        // console.log("_____________", a);
        res.json({ code: 200, msg: a })
      })
      .catch(err => {
        res.json({ code: 4001, msg: err })
      });
   */
  // console.log("doctorArr,tname, tdes,tphoto====+9++++++++=", doctorArr);
  /* let sql1 = `insert into teams values(?,?,?,?,?);`
  let params1 = [null, tname, tdes, tphoto, '0']
  let cb = (err, data) => {
    // console.log(err);
    // console.log(data);
    if (err === null) {
      let tid = data.insertId; // 插入的自增长的ID
      // res.json({
      //   code: 200, msg: '添加团队基本信息成功', data: tid
      // })
 
      // 在成功后，继续去添加团队医生信息，对`teamdoctortable`表操作。
      // console.log(JSON.parse(doctorArr)[0]) //{"did":2,"manager":"2"}
      let arr = JSON.parse(doctorArr)
      let sql2 = `INSERT INTO teamdoctortable VALUES `
      let params2 = [];
      let sqlStr = [];
      // 循环生成插入的语法和参数；　
      arr.forEach(el => {
        sqlStr.push(`(?,?,?,?)`);
        params2.push(null, tid, el.did, el.manager);//null，必须是小写的
      });
      // console.log("sqlStr", sqlStr.join(","));
      sql2 += sqlStr.join(",") + ";"
      // console.log("sql=====", sql2) //INSERT INTO teamdoctortable VALUES (?,?,?,?),(?,?,?,?),(?,?,?,?);
      // console.log(params2);
      let cb2 = (err, data) => {
        console.log(err);
        console.log(data);
        if (err === null) {
          res.json({
            code: 200, msg: '创建医生团队成功',
          })
        } else {
          res.json({
            code: 4001, msg: '创建医生团队失败',
          })
        }
      }
      db.connect(sql2, params2, cb2)
    } else {
      res.json({
        code: 200, msg: '添加团队基本信息失败'
      })
    }
  }
  db.connect(sql1, params1, cb) */

});

module.exports = router;

